package com.boot.mall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.boot.common.constant.AuthConstant;
import com.boot.common.utils.R;
import com.boot.common.vo.MemberResponseVo;
import com.boot.mall.auth.feign.EmsSendFeignService;
import com.boot.mall.auth.feign.MemberRegisterFeignService;
import com.boot.mall.auth.utils.RandomUtil;
import com.boot.mall.auth.vo.UserLoginVo;
import com.boot.mall.auth.vo.UserRegisterVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    private EmsSendFeignService emsSendFeignService;
    @Autowired
    private MemberRegisterFeignService memberRegisterFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes redirectAttributes){
        //1.判断JSR303校验是否出错
        Map<String,String> errors = new HashMap<>();
        if (result.hasErrors()){
            // 将出错的信息封装成Map形式
            errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);
            // 带着出错信息重定向到注册界面
            return "redirect:http://auth.guli.com/reg.html";
        }
        // 校验正确，判断用户输入的验证码是否正确
        System.out.println("校验通过");
        String trueCode = redisTemplate.opsForValue().get(AuthConstant.EMS_CODE_CACHE_PREFIX + vo.getEmail());
        if (!StringUtils.isEmpty(trueCode)){
            // 对验证码进行拆分123456_1621751175027
            if (!trueCode.split("_")[0].equals(vo.getCode())){
                // 验证码不正确，返回注册页面
                errors.put("errors","验证码不正确");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.guli.com/reg.html";
            }else {
                // 验证通过，调用注册方法
                redisTemplate.delete(AuthConstant.EMS_CODE_CACHE_PREFIX + vo.getEmail());
                R res = memberRegisterFeignService.register(vo);
                System.out.println("注册OK");
                return "redirect:http://auth.guli.com/login.html";
            }
        }else {
            // 验证码不正确，返回注册页面
            errors.put("errors","验证码不正确");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.guli.com/reg.html";
        }

    }

    /**
     * 用户登录
     * @param vo
     * @return
     */
    @PostMapping("/login")
    public String login(@Valid UserLoginVo vo, BindingResult result, RedirectAttributes redirectAttributes, HttpSession session){
        //1.判断JSR303校验是否出错
        Map<String,String> errors = new HashMap<>();
        // 校验出错
        if (result.hasErrors()){
            // 将出错的信息封装成Map形式
            errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);
            // 带着出错信息重定向到登录界面
            return "redirect:http://auth.guli.com/login.html";
        }
        // 调用登录方法
        R res = memberRegisterFeignService.login(vo);
        if (res.getCode() == 0){
            // 登录成功
            ObjectMapper mapper = new ObjectMapper();
            MemberResponseVo member = mapper.convertValue(res.get("member"),MemberResponseVo.class);
            System.out.println(member);
            session.setAttribute(AuthConstant.LOGIN_USER,member);
            return "redirect:http://guli.com";
        }else {
            // 登录失败
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.guli.com/login.html";
        }
    }

    /**
     * 发送验证码，将验证码存储到Redis中
     * @param email
     * @return
     */
    @GetMapping("/ems/sendCode")
    @ResponseBody
    public R sendEmailCode(String email){
        // 对邮箱进行简单的判断
        if (!email.endsWith("@qq.com")){
            return R.error("请输入正确的邮箱地址");
        }
        // TODO 判断邮箱是否被注册，被注册不能发邮件

        // 尝试从Redis中获取验证码，判断该邮箱之前是否已经发送过验证码
        String hasSendCode = redisTemplate.opsForValue().get(AuthConstant.EMS_CODE_CACHE_PREFIX + email);
        if (StringUtils.isEmpty(hasSendCode)){
            // Redis中没有当前邮箱号的验证码，调用远程接口发送验证码
            // 生成一个随机的6位数验证码
            String code = RandomUtil.getSixBitRandom();
            // 发送验证码
            emsSendFeignService.sendEmail(code, email);
            System.out.println("验证码发送成功");
            code = code + "_" + System.currentTimeMillis();
            // 发送成功，将验证码存储到Redis中，过期时间5分钟
            redisTemplate.opsForValue().set(AuthConstant.EMS_CODE_CACHE_PREFIX + email,code,5,TimeUnit.MINUTES);
        }else {
            // 当Redis中的验证码不为空，123456_1621751175027，一分钟之后可以再次发送验证码
            String[] codeInRedis = hasSendCode.split("_");
            // 当前的系统时间减去验证码存储的时间，如果大于一分钟，则可以再次发送验证码
            if (System.currentTimeMillis() >= (Long.parseLong(codeInRedis[1]) + (1000 * 60))){
                String code = RandomUtil.getSixBitRandom();
                emsSendFeignService.sendEmail(code,email);
                code = code + "_" + System.currentTimeMillis();
                redisTemplate.opsForValue().set(AuthConstant.EMS_CODE_CACHE_PREFIX + email, code, 5, TimeUnit.MINUTES);
            }else {
                // 距离上次发送时间，不到一分钟，不发送验证码并给出提示
                return R.error("验证码发送过于频繁");
            }
        }
        return R.ok();
    }

}
